﻿import 'package:annotation_route/route.dart';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/r.dart';
import 'package:dk_flutter_module_sale/config/route/sale_in_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/bean/bean_supervisor_visit.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/widget/supervisor_visit_listitem_content.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_api.dart';

/*主管回访列表*/

@ARoute(url: SaleInWidgetRoute.SALE_IN_SUPERVISOR_RETURN_VISIT)
class SupervisorReturnVisit extends CommonPageWithTrack {
  SupervisorReturnVisit(BoostRouteOption option) : super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("收房-主管回访-列表", null);
  }

  @override
  void onInitState(CommonPageBloc pageBloc) {
    Map<String, dynamic> paramsMap = Map();
    paramsMap["page"] = 1;
    paramsMap["page_num"] = 10;
    paramsMap["status"] = "待回访";
    pageBloc.pageHttpGet(
        path: SaleInApi.supervisorReturnVisitList,
        queryMap: paramsMap,
        widgetBuilderByData: (dynamic data) {
          BeanSupervisorVisit visitBean =
              BeanSupervisorVisit.fromJson(data) ?? BeanSupervisorVisit();
          return SupervisorReturnVisitWidget(visitBean, paramsMap, pageBloc);
        });
  }
}

class SupervisorReturnVisitWidget extends StatefulWidget {
  final Map<String, dynamic> paramsMap;
  final CommonPageBloc pageBloc;
  final BeanSupervisorVisit visitBean;

  SupervisorReturnVisitWidget(this.visitBean, this.paramsMap, this.pageBloc);

  @override
  SupervisorReturnVisitState createState() {
    return SupervisorReturnVisitState(
        this.visitBean, this.paramsMap, this.pageBloc);
  }
}

class SupervisorReturnVisitState extends State<SupervisorReturnVisitWidget>
    with SingleTickerProviderStateMixin {
  final List<Tab> tabList = <Tab>[
    Tab(text: '待回访'),
    Tab(text: '已回访'),
    Tab(text: '未回访'),
  ];

  TabController _tabController;

  Map<String, dynamic> paramsMap;
  CommonPageBloc pageBloc;
  BeanSupervisorVisit visitBean;
  DkEasyRefreshController easyRefreshController;
  int selectIndex;
  int pageIndex = 1;
  SupervisorReturnVisitState(this.visitBean, this.paramsMap, this.pageBloc);

  @override
  void initState() {
    super.initState();
    selectIndex = 0;
    _tabController = new TabController(vsync: this, length: 3);
    easyRefreshController = DkEasyRefreshController();
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        selectIndex = _tabController.index;
        print('-----点击了:$selectIndex------');
        switch (_tabController.index) {
          case 0:
            print('tabController.index:$selectIndex');
            paramsMap["status"] = "待回访";

            break;
          case 1:
            print('tabController.index:$selectIndex');
            paramsMap["status"] = "已回访";

            break;
          case 2:
            print('tabController.index:$selectIndex');
            paramsMap["status"] = "未回访";

            break;
        }
        //request
        paramsMap["page"] = 1;
        visitBean.page = 1;
        pageBloc.dataHttpGet(
          path: SaleInApi.supervisorReturnVisitList,
          queryMap: paramsMap,
          handleResult: (dynamic data) {
            BeanSupervisorVisit visitResult =
                BeanSupervisorVisit.fromJson(data) ?? BeanSupervisorVisit();
            visitBean.data.clear();
            visitBean = visitResult;
            setState(() {});
          },
          showLoading: false,
        );
      }
    });
  }

  Future<void> refreshPage() async {
    this.pageIndex = 1;
    paramsMap['page'] = this.pageIndex;
    pageBloc.dataHttpGet(
        path: SaleInApi.supervisorReturnVisitList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          BeanSupervisorVisit visitResult = BeanSupervisorVisit.fromJson(data);
          visitBean = visitResult;
          setState(() {
            easyRefreshController.finishRefresh(success: true);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishRefresh(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishRefresh(success: false);
        });
  }

  Future<void> loadMore() async {
    paramsMap['page'] = (++this.pageIndex);
    pageBloc.dataHttpGet(
        path: SaleInApi.supervisorReturnVisitList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          BeanSupervisorVisit visitResult = BeanSupervisorVisit.fromJson(data);
          visitBean.data.addAll(visitResult.data);
          setState(() {
            easyRefreshController.finishLoad(
                success: true,
                noMore: this.pageIndex >= this.visitBean.lastPage);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }

  @override
  Widget build(BuildContext context) {
    bool noMore = this.pageIndex >= this.visitBean.lastPage;
    return Scaffold(
        appBar: DkAppBar(DKAppBarParams(
          titleContent: "主管回访",
          leading: InkWell(
              onTap: () async => RouteUtil.popOrCloseCurPage(context: context),
              child: Image.asset(R.imagesCommonArrowBackPng)),
          bottom: DkTabBar(TabBarOption.withTabIndicator(
            UnderlineTabIndicator(
              borderSide: BorderSide(width: 2.0, color: Color(0xFF3DBCC6)),
            ),
            tabList,
            selectedLabelColor: Color(0xFF3DBCC6),
            unselectedLabelColor: Color(0xff666666),
            controller: _tabController,
          )),
        )),
        body: Container(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Container(
              width: double.infinity,
              height: 0.5,
              color: Colors.white,
            ),
            Expanded(
              flex: 1,
              child: Container(
                color: Colors.white,
                child: DkRefreshListWidget.custom(
                    controller: easyRefreshController,
                    onLoad: noMore ? null : this.loadMore,
                    onRefresh: this.refreshPage,
                    emptyWidget: this.visitBean.data.length == 0
                        ? LogicPage(PortalConfig.smallEmptyPageParam)
                        : null,
                    slivers: <Widget>[
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                            DataListBean dataListBean = visitBean.data[index];
                            return getVisitItemCell(dataListBean);
                          },
                          childCount: this.visitBean.data.length,
                        ),
                      ),
                    ]),
              ),
            ),
          ],
        )));
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}

Widget getVisitItemCell(DataListBean dataListBean) {
  String listId = "房源编号: " + dataListBean.houseId.toString();
  String name = "业主: " + (dataListBean?.landlordName ?? "");
  String date = "最后跟进时间: " + (dataListBean.lastVisitAt ?? "");
  Color statusColor = stringBlank(dataListBean.statusColor)
      ? Color(0xff1AE0BA)
      : Color(int.parse("0xff" + dataListBean.statusColor));
  double topPadding = stringBlank(dataListBean.houseStatus) ? 0 : 4;
  double leftPadding = stringBlank(dataListBean.houseStatus) ? 0 : 8;

  return Container(
    margin: EdgeInsets.only(bottom: 10),
    color: Colors.white,
    child: InkWell(
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SupervisorListItemContent(
              SupervisorListItemParams(listId, name, date)),
          Container(
            alignment: Alignment.centerRight,
            margin: EdgeInsets.only(right: 15),
            child: Container(
              padding: EdgeInsets.fromLTRB(
                  leftPadding, topPadding, leftPadding, topPadding),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(14),
                  topRight: Radius.circular(14),
                  bottomRight: Radius.circular(14),
                ),
                color: statusColor,
              ),
              child: Text(
                (dataListBean.houseStatus ?? ""),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                ),
              ),
            ),
          ),
        ],
      ),
      onTap: () {
        RouteUtil.goPage(dataListBean.detailUrl);
      },
    ),
  );
}
